import json

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.filters import SearchFilter
from rest_framework.generics import GenericAPIView, ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ViewSet, GenericViewSet,ReadOnlyModelViewSet

from drfapp.models import BOOK,Hero
from drfapp.myfilter import BookFilter, HeroFilter
from drfapp.mypaginator import BookPaginator
from drfapp.serializers import BOOKSerializer,HeroSerializer
from rest_framework.throttling import AnonRateThrottle

# Create your views here.








# 顶配的五种方法-----ModelViewSet
class BOOKView(ModelViewSet):
    queryset = BOOK.objects.filter(is_delete=False)
    serializer_class = BOOKSerializer


    #  1.局部设置过滤查询的后端---settings进行全局配置
    # filter_backends = [DjangoFilterBackend]


    # 2. 全局模糊过滤        drf的全局模糊过滤
    # filter_backends = [SearchFilter]

    # 3. 自定义查询的字段的设置-     局部过滤   ----常用    django过滤
    # filterset_class=BookFilter

    #  4.全局drf过滤   search_fields = ['btitle']


    # django的精准过滤图书表
    # filterset_fields = ('btitle',)
#
#

class HeroView(ModelViewSet):
    queryset = Hero.objects.filter(is_delete=False)
    serializer_class = HeroSerializer


    # 局部分页

    # pagination_class = BookPaginator
    # pagination_class = BookPaginator
    #
    # 全局限流   排序     需要在settings里面配置
    filter_backends = [filters.OrderingFilter]


    # 局部限流
    throttle_classes = [AnonRateThrottle]


    # 全局限流
    # ordering_fields = ['bread']



    #   django的  精准过滤
    # filter_backends = [DjangoFilterBackend]

    # 精准过滤
    # filterset_class=HeroFilter


    # 精准的局部过滤   英雄表
    # filterset_fields=  ('hname',)

#第二种方法：ViewSet
# class BookVIEW(ViewSet):
#     def list(self,request):
#         book=BOOK.objects.filter(is_delete=False)
#         book_ser=BOOKSerializer(instance=book,many=True)
#         return Response({"booklist":book_ser.data})
#     def create(self,request):
#         book=request.data
#         book_ser=BOOKSerializer(data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def retrieve(self,request,id):
#         book=BOOK.objects.get(id=id)
#         book_ser=BOOKSerializer(instance=book)
#         return Response(book_ser.data)
#     def update(self,request,id):
#         book=request.data
#         try:
#             books=BOOK.objects.get(id=id)
#         except:
#             return Response({"msg":"图书不存在"},status=400)
#         book_ser=BOOKSerializer(instance=books,data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def destroy(self,request,id):
#         try:
#              book=BOOK.objects.get(id=id)
#         except:
#             return Response({'msg':"没有该图书"},status=400)
#         book.delete()
#         book.is_delete=True
#         book.save()
#         return Response({'msg':"删除成功"},status=204)
#
# class HeroVIEW(ViewSet):
#     def list(self,request):
#         hero=Hero.objects.filter(is_delete=False)
#         hero_ser=HeroSerializer(instance=hero,many=True)
#         return Response({"booklist":hero_ser.data})
#     def create(self,request):
#         hero=request.data
#         hero_ser=HeroSerializer(data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def retrieve(self,request,id):
#         hero=Hero.objects.get(id=id)
#         hero_ser=HeroSerializer(instance=hero)
#         return Response(hero_ser.data)
#     def update(self,request,id):
#         hero=request.data
#         try:
#             books=Hero.objects.get(id=id)
#         except:
#             return Response({"msg":"图书不存在"},status=400)
#         hero_ser=HeroSerializer(instance=books,data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def destroy(self,request,id):
#         try:
#              hero=Hero.objects.get(id=id)
#         except:
#             return Response({'msg':"没有该图书"},status=400)
#         hero.delete()
#         hero.is_delete=True
#         hero.save()
#         return Response({'msg':"删除成功"},status=204)

# 第三种方法写一遍    GenericViewSet
# class BookRCView(GenericViewSet):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#     def list(self,request):
#         book=self.get_queryset()
#         book_ser=self.get_serializer(instance=book,many=True)
#         return Response({"booklist":book_ser.data})
#     def create(self,request):
#         book=request.data
#         book_ser=self.get_serializer(data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def retrieve(self,request,pk):
#         book=self.get_object()
#         book_ser=self.get_serializer(instance=book)
#         return Response(book_ser.data)
#     def update(self,request,pk):
#         book=request.data
#         try:
#             books=self.get_object()
#         except:
#             return Response({"msg":"图书不存在"},status=400)
#         book_ser=self.get_serializer(instance=books,data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def destroy(self,request,pk):
#         try:
#              book=self.get_object()
#         except:
#             return Response({'msg':"没有该图书"},status=400)
#         book.delete()
#         book.is_delete=True
#         book.save()
#         return Response({'msg':"删除成功"},status=204)
# class HeroRCView(GenericViewSet):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
#     def list(self,request):
#         hero=self.get_queryset()
#         hero_ser=self.get_serializer(instance=hero,many=True)
#         return Response({"booklist":hero_ser.data})
#     def create(self,request):
#         hero=request.data
#         hero_ser=self.get_serializer(data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def retrieve(self,request,id):
#         hero=self.get_object()
#         hero_ser=self.get_serializer(instance=hero)
#         return Response(hero_ser.data)
#     def update(self,request,id):
#         hero=request.data
#         try:
#             heros=self.get_object()
#         except:
#             return Response({"msg":"图书不存在"},status=400)
#         hero_ser=self.get_serializer(instance=heros,data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def destroy(self,request,id):
#         try:
#              hero=self.get_object()
#         except:
#             return Response({'msg':"没有该图书"},status=400)
#         hero.delete()
#         hero.is_delete=False
#         hero.save()
#         return Response({'msg':"删除成功"},status=204)



# 第四种方法：    使用APIView进行增删改查
# class BookRCView(APIView):
#     def get(self,request):
#         book=BOOK.objects.filter(is_delete=False)
#         book_ser=HeroSerializer(instance=book,many=True)
#         return Response(book_ser.data)
#     def post(self,request):
#         book=request.data
#         book_ser=HeroSerializer(data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
# class BookRUD(APIView):
#     def get(self,request,id):
#         books=BOOK.objects.get(id=id)
#         book_ser=HeroSerializer(instance=books)
#         return Response(book_ser.data)
#     def put(self,request,id):
#         book=request.data
#         try:
#             books=BOOK.objects.get(id=id)
#         except:
#             return Response({"没有这本图书"},status=400)
#
#         book_ser=HeroSerializer(instance=books,data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def delete(self,requset,id):
#         try:
#             books=BOOK.objects.get(id=id)
#         except:
#             return Response({"没有该图书"},status=400)
#         books.is_delete=True
#         books.delete()
#         return Response("删除成功")
#
# class HeroRCView(APIView):
#     def get(self,request):
#         hero=Hero.objects.filter(is_delete=False)
#         hero_ser=HeroSerializer(instance=hero,many=True)
#         return Response(hero_ser.data)
#     def post(self,request):
#         hero=request.data
#         hero_ser=HeroSerializer(data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#
# class HeroRUD(APIView):
#     def get(self,request,id):
#         heros=Hero.objects.get(id=id)
#         hero_ser=HeroSerializer(instance=heros)
#         return Response(hero_ser.data)
#     def put(self,request,id):
#         hero=request.data
#         try:
#             heros=Hero.objects.get(id=id)
#         except:
#             return Response({"没有这本图书"},status=400)
#
#         hero_ser=HeroSerializer(instance=heros,data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def delete(self,requset,id):
#         try:
#             heros=Hero.objects.get(id=id)
#         except:
#             return Response({"没有该图书"},status=400)
#         heros.is_delete=True
#         heros.delete()
#         return Response("删除成功")

  #第五种方法    GenericAPIView
# class BookRCView(GenericAPIView):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#
#     def get(self,request):
#         book=self.get_queryset()
#         book_ser=self.get_serializer(instance=book,many=True)
#         return Response(book_ser.data)
#     def post(self,request):
#         book=request.data
#         book_ser=self.get_serializer(data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
# class BookRUDView(GenericAPIView):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#     def get(self,request,pk):
#         books=self.get_object()
#         book_ser=self.get_serializer(instance=books)
#         return Response(book_ser.data)
#     def put(self,request,pk):
#         book=request.data
#         books=self.get_object()
#         book_ser=self.get_serializer(instance=books,data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def delete(self,request,pk):
#         books=self.get_object()
#         books.delete()
#         return Response({"已删除"},status=204)
#
#
#
# class HeroRCView(GenericAPIView):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
#
#     def get(self,request):
#         hero=self.get_queryset()
#         hero_ser=self.get_serializer(instance=hero,many=True)
#         return Response(hero_ser.data)
#     def post(self,request):
#         hero=request.data
#         hero_ser=self.get_serializer(data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
# class HeroRUDView(GenericAPIView):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
#     def get(self,request,pk):
#         heros=self.get_object()
#         hero_ser=self.get_serializer(instance=heros)
#         return Response(hero_ser.data)
#     def put(self,request,pk):
#         hero=request.data
#         heros=self.get_object()
#         hero_ser=self.get_serializer(instance=heros,data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return Response(hero_ser.data)
#     def delete(self,request,pk):
#         heros=self.get_object()
#         heros.delete()
#         return Response({"已删除"},status=204)

  #第六种方法    GenericAPIView   加了五大扩展类
# class BookRCView(GenericAPIView,ListModelMixin,CreateModelMixin):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#     def get(self,request):
#         return self.list(request)
#     def post(self,request):
#         return self.create(request)
# class BookRUDView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#     def get(self,request,pk):
#         return self.retrieve(request)
#     def put(self,request,pk):
#         return self.update(request)
#     def delete(self,request,pk):
#         return Response({"已删除"},status=204)
#
#
#
# class HeroRCView(GenericAPIView,ListModelMixin,CreateModelMixin):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
#     def get(self,request):
#         return self.list(request)
#     def post(self,request):
#         return self.create(request)
# class HeroRUDView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
#     def get(self,request,pk):
#         return self.retrieve(request)
#     def put(self,request,pk):
#         return self.update(request)
#     def delete(self,request,pk):
#         return self.destroy(request)


#第七种方法     ReadOnlyModelViewSet  查一个和查多个
# class BookView(ReadOnlyModelViewSet):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
# class HeroView(ReadOnlyModelViewSet):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer


  #第八种方法
# class BookRCView(ListCreateAPIView):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
# class BookRUDView(RetrieveUpdateDestroyAPIView):
#     queryset = BOOK.objects.filter(is_delete=False)
#     serializer_class = BOOKSerializer
#
#
# class HeroRCView(ListCreateAPIView):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer
# class HeroRUDView(RetrieveUpdateDestroyAPIView):
#     queryset = Hero.objects.filter(is_delete=False)
#     serializer_class = HeroSerializer



# 第九种方法  APIView


# class BookRCView(APIView):
#     def get(self,request):
#         book=BOOK.objects.filter(is_delete=False)
#         book_ser=BOOKSerializer(instance=book,many=True)
#         return Response(book_ser.data)
#     def post(self,request):
#         book=request.data
#         book_ser=BOOKSerializer(data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
# class BookRUD(APIView):
#     def get(self,request,id):
#         books=BOOK.objects.get(id=id)
#         book_ser=BOOKSerializer(instance=books)
#         return Response(book_ser.data)
#     def put(self,request,id):
#         book=request.data
#         try:
#             books=BOOK.objects.get(id=id)
#         except:
#             return Response({"没有这本图书"},status=400)
#
#         book_ser=BOOKSerializer(instance=books,data=book)
#         book_ser.is_valid(raise_exception=True)
#         book_ser.save()
#         return Response(book_ser.data)
#     def delete(self,requset,id):
#         try:
#             books=BOOK.objects.get(id=id)
#         except:
#             return Response({"没有该图书"},status=400)
#         books.is_delete=True
#         books.delete()
#         return Response("删除成功")




# class HeroRCView(View):
#     def get(self,request):
#         hero=Hero.objects.filter(is_delete=False)
#
#         # 当前    每页显示的个数
#         # 个数
#         current_page_num=request.GET.get('number')
#         per_page_nums=request.GET.get('page')
#
#         # 分页器
#         from django.core.paginator import Paginator
#         heros_pa = Paginator(hero,per_page_nums)
#
#         #总页数
#         total_nums = heros_pa.num_pages
#
#         #当前显示的数据
#         heros_page = heros_pa.get_page(current_page_num)
#
#         #
#         hero_list=[]
#         for i in heros_page:
#             hero_list.append({
#                 "hname":i.hname,
#                 "bocomment":i.bocomment,
#                 "bread":i.bread
#             })
#         # hero_ser=HeroSerializer(instance=heros_page,many=True)
#         return JsonResponse({"hero":hero_list,"total_nums":total_nums},safe=False,content_type="application/json;charset utf8")
#     def post(self,request):
#         hero=json.loads(request.body)
#         hero_ser=HeroSerializer(data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return JsonResponse(hero_ser.data)
# #
# class HeroRUD(APIView):
#     def get(self,request,id):
#         heros=Hero.objects.get(id=id)
#         hero_ser=HeroSerializer(instance=heros)
#         return JsonResponse(hero_ser.data)
#     def put(self,request,id):
#         hero=json.loads(request.body)
#         try:
#             heros=Hero.objects.get(id=id)
#         except:
#             return JsonResponse({"没有这本图书"},status=400)
#
#         hero_ser=HeroSerializer(instance=heros,data=hero)
#         hero_ser.is_valid(raise_exception=True)
#         hero_ser.save()
#         return JsonResponse(hero_ser.data)
#     def delete(self,requset,id):
#         try:
#             heros=Hero.objects.get(id=id)
#         except:
#             return JsonResponse({"没有该图书"},status=400)
#         heros.is_delete=True
#         heros.delete()
#         return JsonResponse("删除成功")

class ImageView(View):
    def get(self,request):
        with open('美女.png','rb') as f:
            data=f.read()

        return HttpResponse(data, content_type='image/png')
    def post(self,request):
        data=request.FILES.get('text_file')
        print(data)
        print(type(data))

        file_data=data.read()
        with open(data.name  ,'wb')  as f:
            f.write(file_data)
        return HttpResponse('上传成功了、、、、、、、、')

class ImageViews(APIView):
    def get(self,request):
        with open('美女.png','rb')  as f:
            data=f.read()
        return Response(data,content_type='image/png')
    def post(self,request):
        data=request.data.get('img_file')
        print(data)
        print(type(data))
        # InMemoryUploadedFile
        file_data=data.read()
        with open(data.name , 'wb') as f:
            f.write(file_data)
        return Response("上传成功了")



